package com.JobWebGem.system.controller;

import com.JobWebGem.system.common.BaseResponse;
import com.JobWebGem.system.common.DeleteRequest;
import com.JobWebGem.system.common.ErrorCode;
import com.JobWebGem.system.common.ResultUtils;
import com.JobWebGem.system.exception.BusinessException;
import com.JobWebGem.system.exception.ThrowUtils;
import com.JobWebGem.system.model.dto.resume.ResumeAddRequest;
import com.JobWebGem.system.model.dto.resume.ResumeQueryRequest;
import com.JobWebGem.system.model.dto.resume.ResumeUpdateRequest;
import com.JobWebGem.system.model.entity.Resume;
import com.JobWebGem.system.model.vo.ResumeVO;
import com.JobWebGem.system.service.ResumeService;
import com.JobWebGem.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * 简历接口
 *
 * @author renli
 */
@RestController
@RequestMapping("/resume")
@Slf4j
@Api(tags = "简历接口")
public class ResumeController {

    @Resource
    private UserService userService;

    @Resource
    private ResumeService resumeService;

    // region 增删改查

    /**
     * 创建简历(仅用户)
     *
     * @param resumeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建简历(仅用户)")
    public BaseResponse<Integer> addResume(@RequestBody ResumeAddRequest resumeAddRequest, HttpServletRequest request) {
        if (resumeAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer id = userService.getLoginUser(request).getId();
        Resume resume = new Resume();
        BeanUtils.copyProperties(resumeAddRequest, resume);
        resume.setPhoto(resumeAddRequest.getUserAvatar());
        resume.setSalary(resumeAddRequest.getSalary() + "k");
        resume.setSex(resumeAddRequest.getSex().equals("男") ? 0 : 1);
        resume.setUserId(id);
        boolean result = resumeService.save(resume);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建简历失败");
        return ResultUtils.success(resume.getId());
    }

    /**
     * 删除简历
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除简历(管理员和用户)")
    public BaseResponse<Boolean> deleteResume(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer id = userService.getLoginUser(request).getId();
        boolean result = resumeService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除简历失败");
        return ResultUtils.success(result);
    }

    @PostMapping("/update")
    @ApiOperation("更新简历(仅用户)")
    public BaseResponse<Boolean> updateResume(@RequestBody ResumeUpdateRequest resumeUpdateRequest,
            HttpServletRequest request) {
        if (resumeUpdateRequest == null || resumeUpdateRequest.getResumeId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", resumeUpdateRequest.getResumeId());
        Resume resume = resumeService.getOne(queryWrapper);
        ThrowUtils.throwIf(resume == null, ErrorCode.NOT_FOUND_ERROR, "简历不存在");

        if (resumeUpdateRequest.getUserAvatar() != null && !resumeUpdateRequest.getUserAvatar().equals("")) {
            resume.setPhoto(resumeUpdateRequest.getUserAvatar());
        } else {
            resume.setPhoto(resume.getPhoto());
        }

        if (resumeUpdateRequest.getSex() != null && !resumeUpdateRequest.getSex().equals("")) {
            resume.setSex(resumeUpdateRequest.getSex().equals("男") ? 0 : 1);
        } else {
            resume.setSex(resume.getSex());
        }

        // 使用公共方法设置字段值
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "name");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "birth");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "age");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "phone");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "email");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "marriage");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "political");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "salary");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "college");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "major");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "education");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "experience");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "technology");
        setFieldValueIfEmpty(resumeUpdateRequest, resume, "introduction");

        // 设置特定值
        BeanUtils.copyProperties(resumeUpdateRequest, resume);
        resume.setSalary(resumeUpdateRequest.getSalary() + "k");

        // 更新简历
        boolean result = resumeService.updateById(resume);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新简历失败");
        return ResultUtils.success(result);
    }

    /**
     * 获取所有简历
     *
     * @return Page<Job>
     */
    @PostMapping("/get/all")
    @ApiOperation("获取所有简历（仅管理员）")
    public BaseResponse<Page<ResumeVO>> listResumeByAll(@RequestBody ResumeQueryRequest resumeQueryRequest,
            HttpServletRequest request) {
        long current = resumeQueryRequest.getCurrent() == 0 ? 1 : resumeQueryRequest.getCurrent();
        long pageSize = resumeQueryRequest.getPageSize() == 0 ? 10 : resumeQueryRequest.getPageSize();

        Page<Resume> paramPage = new Page<>(current, pageSize);

        Page<ResumeVO> resumePage = resumeService.getByAll(paramPage, resumeQueryRequest);
        return ResultUtils.success(resumePage);
    }

    /**
     * 获取用户自己的简历
     *
     * @return Page<Job>
     */
    @PostMapping("/get/my")
    @ApiOperation("获取用户自己的简历(仅自己)")
    public BaseResponse<Page<ResumeVO>> listResumeByMy(@RequestBody ResumeQueryRequest resumeQueryRequest,
            HttpServletRequest request) {
        long current = resumeQueryRequest.getCurrent() == 0 ? 1 : resumeQueryRequest.getCurrent();
        long pageSize = resumeQueryRequest.getPageSize() == 0 ? 10 : resumeQueryRequest.getPageSize();

        Integer userId = userService.getLoginUser(request).getId();

        Page<Resume> paramPage = new Page<>(current, pageSize);

        Page<ResumeVO> resumePage = resumeService.getByMy(paramPage, resumeQueryRequest, userId);
        if (resumePage.getTotal() == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "简历不存在");
        }
        return ResultUtils.success(resumePage);
    }

    // endregion

    /**
     * HR查看投递用户的简历
     *
     * @return Page<Job>
     */
    @PostMapping("/get/user")
    @ApiOperation("HR查看投递用户的简历（根据id查）")
    public BaseResponse<ResumeVO> listResumeById(@RequestBody ResumeQueryRequest resumeQueryRequest) {
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", resumeQueryRequest.getResumeId());
        Resume resume = resumeService.getOne(queryWrapper);
        if (resume == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "简历不存在");
        }
        ResumeVO resumeVO = new ResumeVO();
        // 先复制所有基础属性
        BeanUtils.copyProperties(resume, resumeVO);
        // 设置resumeId
        resumeVO.setResumeId(resume.getId());
        // 设置性别描述
        if (resume.getSex() == 1) {
            resumeVO.setSex("女");
        } else if (resume.getSex() == 0) {
            resumeVO.setSex("男");
        }
        // 设置头像
        resumeVO.setUserAvatar(resume.getPhoto());
        return ResultUtils.success(resumeVO);
    }

    /**
     * 如果 `resumeUpdateRequest` 中的字段为空或为零，则从 `updateResume` 中设置相应的值。
     *
     * @param resumeUpdateRequest
     * @param updateResume
     * @param fieldName
     */
    public static void setFieldValueIfEmpty(ResumeUpdateRequest resumeUpdateRequest, Resume updateResume,
            String fieldName) {
        Field field = ReflectionUtils.findField(ResumeUpdateRequest.class, fieldName);
        ReflectionUtils.makeAccessible(field);
        Object value = ReflectionUtils.getField(field, resumeUpdateRequest);
        if (value == null || (value instanceof String && ((String) value).isEmpty())
                || (value instanceof Number && ((Number) value).intValue() == 0)) {
            Field updateField = ReflectionUtils.findField(Resume.class, fieldName);
            ReflectionUtils.makeAccessible(updateField);
            Object updateValue = ReflectionUtils.getField(updateField, updateResume);
            ReflectionUtils.setField(field, resumeUpdateRequest, updateValue);
        }
    }
}
